package org.linlinjava.litemall.admin.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.linlinjava.litemall.admin.dto.AdminShopMerchandiseJobDTO;
import org.linlinjava.litemall.core.notify.AwsNotifyService;
import org.linlinjava.litemall.db.dao.LitemallAdminMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商店商品工作
 * 门店货品定时任务
 *
 * @author yliyun
 * @date 2022/11/25
 */
@Slf4j
@Data
@RequiredArgsConstructor
@Component
@Configuration
public class ShopMerchandiseJob implements Job {

    /**
     * litemall商店商品服务
     */
    private final LitemallShopMerchandiseService litemallShopMerchandiseService;

    /**
     * litemall商品服务
     */
    private final LitemallMerchandiseService litemallMerchandiseService;

    private final LitemallAdminMapper litemallAdminMapper;

    /**
     * aws通知服务
     */
    private final AwsNotifyService awsNotifyService;

    private final LitemallShopService litemallShopService;

    //时间表达式  每天上午10:15触发
    private String cron = "0 15 10 ? * *";
    /**
     * 自卫队
     */
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private String parameter;


    @SneakyThrows
    public void doTask() {
            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            //任务逻辑
            log.info("---------------门店货品定时任务 start-------------------");
            log.info("当前时间为：{}",sdf.format(new Date()));
            log.info("当前执行任务名称："+parameter);
            //检查所有需要提示的预警
            List<LitemallShopMerchandise> litemallShopMerchandiseList = litemallShopMerchandiseService.list(Wrappers.lambdaQuery(LitemallShopMerchandise.class)
                    .apply("warn_number >= number")
                    .isNotNull(LitemallShopMerchandise::getWarnNumber)
            ).stream().collect(Collectors.toList());

            List<AdminShopMerchandiseJobDTO> adminShopMerchandiseJobDTOS = litemallShopMerchandiseList.stream().map(shopMerchandise -> {
                AdminShopMerchandiseJobDTO adminShopMerchandiseJobDTO = AdminShopMerchandiseJobDTO.builder()
                        .shopId(shopMerchandise.getShopId())
                        .build();
                adminShopMerchandiseJobDTO.setMsgTemplate(
                        litemallShopService.findById(shopMerchandise.getShopId()).getName()+"「Product："+litemallMerchandiseService.findById(shopMerchandise.getMerchandiseId()).getName()+"，Alert threshold："+shopMerchandise.getWarnNumber()+"，Inventory："+shopMerchandise.getNumber()+"」\r\n"
                );
                return adminShopMerchandiseJobDTO;
            }).collect(Collectors.toList());

            //将所有门店的货品和店长统计
            Map<Integer, List<AdminShopMerchandiseJobDTO>> collect = adminShopMerchandiseJobDTOS.stream()
                .collect(Collectors.groupingBy(AdminShopMerchandiseJobDTO::getShopId));

            Iterator<Map.Entry<Integer, List<AdminShopMerchandiseJobDTO>>> iterator = collect.entrySet().iterator();
            Map map = new HashMap<>();
            while (iterator.hasNext()) {
                Map.Entry<Integer, List<AdminShopMerchandiseJobDTO>> entry = iterator.next();
                String conent = "";
                for (AdminShopMerchandiseJobDTO adminShopMerchandiseJobDTO : entry.getValue()) {
                    conent+=adminShopMerchandiseJobDTO.getMsgTemplate();
                }
                map.put(entry.getKey(),conent);
                //System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue());
            }
            map.forEach((k,v)->{
                //得到店长和副店长的用户
                List<LitemallAdmin> litemallAdmins = litemallAdminMapper.selectJoinList(LitemallAdmin.class, new MPJLambdaWrapper<LitemallAdmin>()
                        .selectAll(LitemallAdmin.class)
                        .leftJoin(LitemallShop.class, LitemallShop::getId, LitemallAdmin::getShopId)
                        .eq(LitemallShop::getId, k)
                ).stream().filter(adminUser->Arrays.stream(adminUser.getRoleIds()).anyMatch(roleId->roleId==4||roleId==5)).collect(Collectors.toList());
                if(CollUtil.isNotEmpty(litemallAdmins)){
                    litemallAdmins.stream().forEach(litemallAdmin -> {
                        //发送邮件提醒
                        awsNotifyService.noticeMail("Store goods warning reminder",
                                "Please check the goods in the store. They are out of stock!\r\n"+v,
                                "", litemallAdmin.getEmail());
                    });
                }
                System.out.println(v);
            } );
        };


    @Override
    public void execute(JobExecutionContext jobExecutionContext){
        this.doTask();
    }
}
